"use strict";
const electron = require("electron");
const path = require("path");
let win;
let progressInterval;
let width = 1200;
let height = 800;
const createWindow = () => {
  win = new electron.BrowserWindow({
    width,
    height,
    frame: false,
    titleBarStyle: "hidden",
    webPreferences: {
      contextIsolation: true,
      // 是否开启隔离上下文
      nodeIntegration: true,
      // 渲染进程使用Node API
      preload: path.join(__dirname, "./preload.js")
      // 需要引用js文件
    }
  });
  if (process.env.NODE_ENV !== "development") {
    win.loadFile(path.join(__dirname, "./index.html"));
    win.webContents.openDevTools();
  } else {
    let url = "http://localhost:5173";
    win.loadURL(url);
    win.webContents.openDevTools();
  }
  const INCREMENT = 0.03;
  const INTERVAL_DELAY = 100;
  let c = 0;
  progressInterval = setInterval(() => {
    win.setProgressBar(c);
    if (c < 2) {
      c += INCREMENT;
    } else {
      c = -INCREMENT * 5;
    }
  }, INTERVAL_DELAY);
};
const dockMenu = electron.Menu.buildFromTemplate([
  {
    label: "New Window",
    click() {
      console.log("New Window");
    }
  },
  {
    label: "New Window with Settings",
    submenu: [
      { label: "Basic" },
      { label: "Pro" }
    ]
  },
  { label: "New Command..." }
]);
function showNotification(msg) {
  let options = {
    title: "通知",
    body: msg,
    silent: false,
    urgency: "critical",
    closeButtonText: "关闭",
    hasReply: true
  };
  let notification = new electron.Notification(options);
  if (electron.Notification.isSupported()) {
    notification.show();
  } else {
    console.log("不支持通知");
  }
  notification.on("click", () => {
    console.log("Notification clicked");
  });
  notification.on("close", () => {
    console.log("Notification closed");
  });
  notification.on("reply", (event, reply) => {
    console.log("Notification replied", reply);
  });
}
electron.ipcMain.on("setMinSize", (event, title) => {
  console.log("主线程监听到了vue传过来的数据", title);
  win.unmaximize();
});
electron.ipcMain.on("setMaxSize", () => {
  console.log("主线程监听到了vue传放大的信号");
  if (win.isMaximized()) {
    win.restore();
  } else {
    win.maximize();
  }
});
electron.ipcMain.on("setNotify", (event, msg) => {
  console.log("主线程已接收到", msg);
  showNotification(msg);
});
electron.app.whenReady().then(() => {
  if (process.platform === "darwin") {
    electron.app.dock.setMenu(dockMenu);
  }
  createWindow();
  electron.app.on("activate", () => {
    if (electron.BrowserWindow.getAllWindows().length === 0)
      createWindow();
  });
});
electron.app.on(
  "window-all-closed",
  () => {
    if (process.platform !== "darwin") {
      electron.app.quit();
    }
  }
);
electron.app.on("open-url", function(event, url) {
  event.preventDefault();
  console.log(`Received URL: ${url}`);
});
electron.app.on("before-quit", () => {
  clearInterval(progressInterval);
});
